package com.qqim.server;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 服务端主程序
 */
public class ServerMain {
    private static final Logger logger = LoggerFactory.getLogger(ServerMain.class);
    
    private static final String DEFAULT_HOST = "0.0.0.0";
    private static final int DEFAULT_PORT = 8888;
    
    private QQIMServer server;
    private JFrame frame;
    private JTextArea logArea;
    private JTextField hostField;
    private JTextField portField;
    private JButton startButton;
    private JButton stopButton;
    private JLabel statusLabel;
    private JLabel clientCountLabel;
    
    public static void main(String[] args) {
        // 设置系统外观
        try {
            for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (Exception e) {
            logger.warn("设置系统外观失败", e);
        }
        
        SwingUtilities.invokeLater(() -> {
            new ServerMain().createAndShowGUI();
        });
    }
    
    private void createAndShowGUI() {
        frame = new JFrame("QQ即时通信服务端");
        frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        frame.setSize(800, 600);
        frame.setLocationRelativeTo(null);
        
        // 窗口关闭事件
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                onExit();
            }
        });
        
        initComponents();
        layoutComponents();
        bindEvents();
        
        frame.setVisible(true);
        
        addLog("服务端启动完成，等待配置...");
    }
    
    private void initComponents() {
        // 配置面板组件
        hostField = new JTextField(DEFAULT_HOST);
        hostField.setPreferredSize(new Dimension(120, 25));
        
        portField = new JTextField(String.valueOf(DEFAULT_PORT));
        portField.setPreferredSize(new Dimension(80, 25));
        
        startButton = new JButton("启动服务");
        stopButton = new JButton("停止服务");
        stopButton.setEnabled(false);
        
        // 状态显示组件
        statusLabel = new JLabel("状态: 未启动");
        statusLabel.setForeground(Color.RED);
        
        clientCountLabel = new JLabel("在线用户: 0");
        
        // 日志显示组件
        logArea = new JTextArea();
        logArea.setEditable(false);
        logArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
        logArea.setBackground(Color.BLACK);
        logArea.setForeground(Color.GREEN);
    }
    
    private void layoutComponents() {
        frame.setLayout(new BorderLayout());
        
        // 顶部配置面板
        JPanel configPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        configPanel.setBorder(BorderFactory.createTitledBorder("服务器配置"));
        
        configPanel.add(new JLabel("监听地址:"));
        configPanel.add(hostField);
        configPanel.add(new JLabel("端口:"));
        configPanel.add(portField);
        configPanel.add(startButton);
        configPanel.add(stopButton);
        
        // 状态面板
        JPanel statusPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        statusPanel.add(statusLabel);
        statusPanel.add(Box.createHorizontalStrut(20));
        statusPanel.add(clientCountLabel);
        
        // 顶部面板
        JPanel topPanel = new JPanel(new BorderLayout());
        topPanel.add(configPanel, BorderLayout.NORTH);
        topPanel.add(statusPanel, BorderLayout.SOUTH);
        
        // 日志面板
        JPanel logPanel = new JPanel(new BorderLayout());
        logPanel.setBorder(BorderFactory.createTitledBorder("服务器日志"));
        logPanel.add(new JScrollPane(logArea), BorderLayout.CENTER);
        
        frame.add(topPanel, BorderLayout.NORTH);
        frame.add(logPanel, BorderLayout.CENTER);
    }
    
    private void bindEvents() {
        startButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                startServer();
            }
        });
        
        stopButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                stopServer();
            }
        });
    }
    
    private void startServer() {
        try {
            String host = hostField.getText().trim();
            int port = Integer.parseInt(portField.getText().trim());
            
            if (host.isEmpty()) {
                JOptionPane.showMessageDialog(frame, "请输入监听地址", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            
            if (port < 1 || port > 65535) {
                JOptionPane.showMessageDialog(frame, "端口必须在1-65535之间", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            
            server = new QQIMServer(host, port, this);
            server.start();
            
            startButton.setEnabled(false);
            stopButton.setEnabled(true);
            hostField.setEnabled(false);
            portField.setEnabled(false);
            
            statusLabel.setText("状态: 运行中");
            statusLabel.setForeground(Color.GREEN);
            
            addLog("服务器启动成功，监听地址: " + host + ":" + port);
            
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(frame, "端口必须是数字", "错误", JOptionPane.ERROR_MESSAGE);
        } catch (IOException e) {
            JOptionPane.showMessageDialog(frame, "启动服务器失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            logger.error("启动服务器失败", e);
        }
    }
    
    private void stopServer() {
        if (server != null) {
            server.stop();
            server = null;
        }
        
        startButton.setEnabled(true);
        stopButton.setEnabled(false);
        hostField.setEnabled(true);
        portField.setEnabled(true);
        
        statusLabel.setText("状态: 已停止");
        statusLabel.setForeground(Color.RED);
        
        clientCountLabel.setText("在线用户: 0");
        
        addLog("服务器已停止");
    }
    
    private void onExit() {
        int option = JOptionPane.showConfirmDialog(
            frame,
            "确定要关闭服务器吗？",
            "确认退出",
            JOptionPane.YES_NO_OPTION
        );
        
        if (option == JOptionPane.YES_OPTION) {
            if (server != null) {
                server.stop();
            }
            System.exit(0);
        }
    }
    
    /**
     * 添加日志信息（由服务器调用）
     */
    public void addLog(String message) {
        SwingUtilities.invokeLater(() -> {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String timestamp = sdf.format(new Date());
            String logMessage = String.format("[%s] %s%n", timestamp, message);
            
            logArea.append(logMessage);
            logArea.setCaretPosition(logArea.getDocument().getLength());
        });
    }
    
    /**
     * 更新客户端数量（由服务器调用）
     */
    public void updateClientCount(int count) {
        SwingUtilities.invokeLater(() -> {
            clientCountLabel.setText("在线用户: " + count);
        });
    }
} 